package com.scuec.groupfive.mapper;

import com.scuec.groupfive.entity.Favorite_z;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface Favorite_zMapper {

    // 查询用户收藏列表
    @Select("SELECT " +
            "id, " +
            "user_id AS userId, " +
            "question_id AS questionId, " +
            "folder_id AS folderId, " +
            "status, " +
            "created_at AS createdAt, " +
            "updated_at AS updatedAt " +
            "FROM favorites " +
            "WHERE user_id = #{userId} AND status = 1")
    List<Favorite_z> selectByUserId(Long userId);

    // 检查收藏是否存在（不考虑状态）
    @Select("SELECT COUNT(1) FROM favorites WHERE user_id = #{param1} AND question_id = #{param2}")
    int checkExists(@Param("userId") Long userId, @Param("questionId") Long questionId);

    // 检查收藏是否存在（只检查状态为1的记录）
    @Select("SELECT COUNT(1) FROM favorites WHERE user_id = #{param1} AND question_id = #{param2} AND status = 1")
    int exists(@Param("userId") Long userId, @Param("questionId") Long questionId);

    // 添加收藏
    @Insert("INSERT INTO favorites(user_id, question_id, folder_id, status, created_at, updated_at) " +
            "VALUES (#{userId}, #{questionId}, #{folderId}, #{status}, #{createdAt}, #{updatedAt})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Favorite_z favorite);

    // 移除收藏（使用数据库当前时间）
    @Update("UPDATE favorites SET status = 0, updated_at = NOW() " +
            "WHERE user_id = #{userId} AND question_id = #{questionId} AND status = 1")
    int delete(@Param("userId") Long userId, @Param("questionId") Long questionId);

    @Update("UPDATE favorites SET status = #{status}, updated_at = NOW() WHERE user_id = #{userId} AND question_id = #{questionId}")
    int updateStatus(@Param("userId") Long userId, @Param("questionId") Long questionId, @Param("status") int status);

}